import cv2
import numpy as np

img1 = cv2.imread('D:\\gan.jpg')
#缩小图像
img = cv2.pyrDown(img1)
#滤波处噪音
img_gs = cv2.GaussianBlur(img,(5,5),0)
#获取图像的hsv
hsv = cv2.cvtColor(img_gs,cv2.COLOR_BGR2HSV)
#设定阈值范围
lower_hsv = np.array([0,110,46])
high_hsv = np.array([10,255,255])
range = cv2.inRange(hsv.copy(),lower_hsv,high_hsv)
range,contours,hierarchy = cv2.findContours(range,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
if len(contours)>0:
    c= max(contours, key=cv2.contourArea)


    #画矩形
    x, y, w, h = cv2.boundingRect(c)
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 255), 2)
    #矩形参数
    print("矩形长度和宽度：")

    print(w,h)

    #画最小矩形
    ix, iy, iw, ih = cv2.boundingRect(c)#最小矩形的xywh
    min_rect = cv2.minAreaRect(c)#找到面积最小的矩形
    # min_rect = ((min_rect[0][0],min_rect[0][1],min_rect[1][0],min_rect[1][1]),0)
    box = cv2.boxPoints(min_rect)
    box = np.int0(box)
    # 输出矩形
    cv2.drawContours(img, [box], 0, (0, 255, 0), 3)
    print("最小矩形长度和宽度：")
    print(min_rect[1][0], min_rect[1][1])
    # 用绿色显示最小圆
    (x, y), radius = cv2.minEnclosingCircle(c)
    #圆心和半径
    center = (int(x), int(y))
    radius = int(radius)

    print("圆心坐标和半径")
    print(x, y, radius)
    cv2.circle(img, center, radius, (255, 255, 255), 2)


leftmost = tuple(c[c[:,:,0].argmin()][0])
rightmost = tuple(c[c[:,:,0].argmax()][0])
topmost = tuple(c[c[:,:,1].argmin()][0])
bottommost = tuple(c[c[:,:,1].argmax()][0])

print('四个极点')
print(leftmost,rightmost,topmost,bottommost)

cv2.imshow('lunkuo', range)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()